package com.wanmait.spacesys.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wanmait.spacesys.util.DbHelper;
import com.wanmait.spacesys.vo.Config;

public class ConfigDAO {

	public List<Config> findAll() {
		List<Config> configs = new ArrayList<>();
		String sql = "SELECT config.* FROM config where enable=1";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				Config config = new Config();
				config.setDescription(rs.getString(2));
				config.setId(rs.getInt(1));
				config.setKey(rs.getString(3));
				config.setValue(rs.getString(4));
				config.setEnable(rs.getBoolean(5));
				configs.add(config);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			DbHelper.close(rs,ps,conn);
		}
		return configs;
	}
	public void save(Config config) {
		System.out.println(config);
		String sql = "UPDATE config set description=?,`KEY`=?,`VALUE`=? where id =?";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			DbHelper.update(sql, config.getDescription(),config.getKey(),config.getValue(),config.getId());
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			DbHelper.close(ps,conn);
		}
	}
	public void delConfig(Integer id) {
		String sql = "update config set enable=0 where id=?";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			DbHelper.update(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			DbHelper.close(ps,conn);
		}
	}
	public void addConfig(String des, String key, String val) {
		String sql = "insert into config (description,`key`,`value`) VALUES (?,?,?)";
		Connection conn = DbHelper.getConnection();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			DbHelper.update(sql,des,key,val );
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			DbHelper.close(ps,conn);
		}
	}

}
